package com.eleventwelve.iris.web.controller;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.opentides.bean.FileInfo;
import org.opentides.util.StringUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.eleventwelve.iris.entity.Patient;
import com.eleventwelve.iris.service.PatientService;
import com.eleventwelve.iris.utilities.ImageUtil;

public class PatientImageController extends AbstractController {
	private static final Logger _log = Logger
			.getLogger(UserImageController.class);
	private PatientService patientService;

	@Override
	public ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Long patientId = StringUtil.convertToLong(request.getParameter("patientId"),
				-1);
		String imageSize = request.getParameter("imageSize");

		@SuppressWarnings("deprecation")
		String defaultImage = request.getRealPath("")
				+ "/images/iris/iris-male.jpg";
		@SuppressWarnings("deprecation")
		String defaultFemaleImg = request.getRealPath("")
				+ "/images/iris/iris-female.jpg";

		long updateDate = 0;
		byte[] barray = null;
		// long modified = request.getDateHeader("If-Modified-Since");
		OutputStream outputStream = response.getOutputStream();

		try {
			Patient patient = (Patient) patientService.load(patientId);
			if (patient != null && patient.getFiles() != null
					&& !patient.getFiles().isEmpty()) {
				FileInfo fileInfo = patient.getFiles().get(
						patient.getFiles().size() - 1);
				updateDate = fileInfo.getUpdateDate().getTime();
				/*
				 * if (updateDate > modified) {
				 */
				String filePath = fileInfo.getFullPath();

				if ("mini".equals(imageSize)) {
					barray = ImageUtil.loadImage(ImageUtil.buildFileName(
							filePath, "_mini.png"));
				} else if ("thumb".equals(imageSize)) {
					barray = ImageUtil.loadImage(ImageUtil.buildFileName(
							filePath, "_thumb.png"));
				} else if ("large".equals(imageSize)) {
					barray = ImageUtil.loadImage(ImageUtil.buildFileName(
							filePath, "_large.png"));
				} else {
					barray = ImageUtil.loadImage(filePath);
				}

				if (barray == null) {
					barray = getDefaultImg(patient, defaultImage, defaultFemaleImg);
				}

				if (barray != null) {
					response.setContentType("image/jpeg");
					response.setHeader("Cache-Control", "public");
					response.addDateHeader("Last-Modified", updateDate);
					outputStream.write(barray);
				}
				/*
				 * } else { // just use browser cache
				 * response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); }
				 */
			} else {
				// no image uploaded, use default image
				/*
				 * if (modified > 0) { // from cache
				 * response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); }
				 * else {
				 */
				// read image
				barray = getDefaultImg(patient, defaultImage, defaultFemaleImg);
				if (barray != null) {
					response.setContentType("image/jpeg");
					response.setHeader("Cache-Control", "public");
					response.addDateHeader("Last-Modified",
							System.currentTimeMillis());
					outputStream.write(barray);
				}
				/*
				 * }
				 */
			}
		} catch (Exception e) {
			_log.error("Failed to load image.", e);
		} finally {
			outputStream.flush();
			outputStream.close();
		}
		return null;
	}

	private byte[] getDefaultImg(Patient patient, String defaultMale,
			String defaultFemale) {
		if (patient != null && !StringUtil.isEmpty(patient.getGender().getValue())
				&& patient.getGender().getValue().equals("Female"))
			return ImageUtil.loadImage(defaultFemale);

		return ImageUtil.loadImage(defaultMale);
	}

	public void setPatientService(PatientService patientService) {
		this.patientService = patientService;
	}

}
